<template>
    <div class="page-1">
        <PageTitle></PageTitle>

        <WizardSteps :active="1" />

        <section class="card-img">
            <img v-show="img" :src="img" alt="insertcard" draggable="false" />
            <p :class="{ 'tips-text': true, 'text-pre': textPre }">
                <span :class="{ loading: isInit }">{{ tipText }}</span>
            </p>
        </section>

        <section class="simSettings" v-if="showSimSetting">
            <div class="simSettings-title">
                <b>{{ $t('wizard.version2.simSet') }}</b>
            </div>

            <div class="simSettings-form">
                <el-form ref="apnRef" :rules="apnRules" :model="simSettingsForm" label-width="155px" :label-position="labelPosition">
                    <!-- Profile Name -->
                    <el-form-item :label="$t('wizard.version2.profileName') + ':'">
                        <div class="setWitdh">
                            <el-input v-model="simSettingsForm.profileName" disabled></el-input>
                        </div>
                    </el-form-item>

                    <!-- PDP Type  -->
                    <el-form-item :label="$t('wizard.version2.pdpType') + ':'">
                        <div class="setWitdh">
                            <el-select id="protocolSelect" v-model="simSettingsForm.pdpType">
                                <div id="protocolOptions">
                                    <el-option :value="protoItem.value" :label="protoItem.label" v-for="(protoItem, index) in protocolOptions" :key="index"></el-option>
                                </div>
                            </el-select>
                        </div>
                    </el-form-item>

                    <!-- APN -->
                    <el-form-item :label="$t('netWork.apnSettings.apnAPN') + ':'" prop="apnNameInput">
                        <div class="setWitdh">
                            <el-input v-model="simSettingsForm.apnNameInput"></el-input>
                        </div>
                    </el-form-item>

                    <template v-if="simSettingsForm.aType != '0'">
                        <!-- User Name -->
                        <el-form-item :label="$t('common.username') + ':'" prop="apnUsernameInput">
                            <div class="setWitdh">
                                <el-input v-model="simSettingsForm.apnUsernameInput"></el-input>
                            </div>
                        </el-form-item>

                        <!-- password -->
                        <el-form-item :label="$t('common.password') + ':'" prop="apnPasswordInput">
                            <div class="setWitdh">
                                <el-input v-model="simSettingsForm.apnPasswordInput" :type="isHidePwd ? 'password' : ''" maxLength="63">
                                    <template slot="suffix">
                                        <div :class="isHidePwd ? 'my-eye-hide' : 'my-eye-reveal'" @click="isHidePwd = !isHidePwd"></div>
                                    </template>
                                </el-input>
                            </div>
                        </el-form-item>
                    </template>

                    <!-- Authentication Type -->
                    <el-form-item :label="$t('netWork.apnSettings.apnAuthenticationType') + ':'">
                        <div class="setWitdh">
                            <el-select id="authTypeSelect" v-model="simSettingsForm.aType">
                                <div id="authTypeOptions">
                                    <el-option :value="authItem.value" :label="authItem.label" v-for="(authItem, index) in authTypeOptions" :key="index"></el-option>
                                </div>
                            </el-select>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </section>

        <section class="btn-content">
            <el-button type="primary" @click="nextClick">{{ nextButton }}</el-button>
        </section>
    </div>
</template>

<script>
import { cloneDeep, isEqual } from 'lodash-es';

import PageTitle from './PageTitle.vue';
import WizardSteps from './WizardSteps.vue';
import { WIZARD_ROUTE, setWizardHistory, textObj } from './wizard.data';
import watchWindow from '@/hooks/watchWindow';
import { getByteLength } from '@/utils/common';
import { errorCode } from '@/constant/dict';
import { REGULAR_RULES } from '@/constant/regularRules';
import { getSystemConfig } from '@/api/system';

export default {
    name: 'ConnectionDetection',
    extends: watchWindow,
    components: {
        PageTitle,
        WizardSteps
    },
    data() {
        const apnName = (rule, value, callback) => {
            if (value) {
                if (getByteLength(value) > 62) {
                    callback(new Error(this.$t('errorTips.maxLength')));
                } else {
                    if (REGULAR_RULES.LETTER_OR_NUMBER_OR_POINT_HYPHEN.test(value)) {
                        if (REGULAR_RULES.START_END_MUST_LETTER_OR_NUMBER.test(value)) {
                            callback();
                        } else {
                            callback(new Error(this.$t('errorTips.startAndEndMustLetterOrNumber')));
                        }
                    } else {
                        callback(new Error(this.$t('errorTips.inputValidatorTips')));
                    }
                }
            } else {
                callback();
            }
        };

        const apnUserName = (rule, value, callback) => {
            if (value) {
                const result = this.$nameCheck(value, 63);
                if (result == errorCode.BYTEERR) {
                    callback(new Error(this.$t('errorTips.maxLength')));
                } else if (!result || value.includes(',')) {
                    callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        const apnPassword = (rule, value, callback) => {
            if (value) {
                const result = this.$checkStr(value, false, true, true, false, 63, 33);
                if (result == errorCode.BYTEERR) {
                    callback(new Error(this.$t('errorTips.maxLength')));
                } else if (result == errorCode.STRERR || result == errorCode.ACCIIERR || value.includes(',')) {
                    callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        return {
            labelPosition: 'right',
            haveSim: false,
            fetchMainStatusTimer: null,
            noSimTips: textObj().noSimTips,
            haveSimTips: this.$t('wizard.haveSimTips'),
            simInitTips: this.$t('wizard.simInitTips'),
            simLocktTips: this.$t('dataBoard.lockSIMCardTitle'),
            insertcardImg: require('@/assets/images/wizard/insertcard.png'),
            havecardImg: require('@/assets/images/wizard/havesimcard.png'),
            simInitImg: require('@/assets/images/wizard/initializing.png'),
            simLockImg: require('@/assets/images/wizard/locked.png'),
            isBeingDestroyed: false,
            img: '',
            tipText: '',
            isInit: false,
            nextButton: this.$t('common.nextButton'),
            simSettingsForm: {
                profileName: 'APN1',
                apnNameInput: '',
                apnPasswordInput: '',
                apnUsernameInput: '',
                aType: '0',
                pdpType: '0'
            },
            simSettingsFormDeepClone: {
                profileName: 'APN1',
                apnNameInput: '',
                apnPasswordInput: '',
                apnUsernameInput: '',
                aType: '0',
                pdpType: '0'
            },
            showSimSetting: false,
            apnRules: {
                apnNameInput: [{ validator: apnName, trigger: 'blur' }],
                apnUsernameInput: [{ validator: apnUserName, trigger: ['blur', 'change'] }],
                apnPasswordInput: [{ validator: apnPassword, trigger: ['blur', 'change'] }]
            },
            authTypeOptions: [
                {
                    label: 'NONE',
                    value: '0'
                },
                {
                    label: 'PAP',
                    value: '1'
                },
                {
                    label: 'CHAP',
                    value: '2'
                }
            ],
            protocolOptions: [
                {
                    label: 'IPv4',
                    value: '0'
                },
                {
                    label: 'IPv6',
                    value: '1'
                },
                {
                    label: 'IPv4v6',
                    value: '2'
                }
            ],
            getApn: true,
            isHidePwd: true
        };
    },
    methods: {
        // 下一步回调
        async nextClick() {
            this.toNext();
        },
        toNext() {
            this.isBeingDestroyed = true;
            this.$router.replace(WIZARD_ROUTE.BasicSettings);
            setWizardHistory(WIZARD_ROUTE.BasicSettings);
        },
        // 获取主状态
        async fetchMainStatus() {
            if (this.isBeingDestroyed) return;

            // 获取 MODULE_LTE_MAIN_STATUS 的值
            const { main_status: manStatus } = await getSystemConfig();

            // 设置等待时间
            let waitTime = 1000;

            // 更新 haveSim 的值
            this.haveSim = !['sim_not_ready'].includes(manStatus);

            // 判断显示状态
            if (this.haveSim) {
                const simLock = ['need_pin', 'need_puk', 'sim_locked'].includes(manStatus);
                // const simInit = ['modem_init', 'sim_init'].includes(manStatus);

                // 卡初始化提示
                // if (simInit) {
                //     this.getApn = true;
                //     this.updataStatus('simInit');
                //     waitTime = 1000;
                // }
                if(simLock){ // 锁卡提是
                    this.updataStatus('simLock');
                }else{
                    // 有卡提示
                    this.updataStatus('haveSim');
                    waitTime = 10000;
                }
            } else { // 无卡提示
                this.getApn = true;
                this.updataStatus('noSim');
            }

            // 等待一定时间后递归调用 fetchMainStatus
            await new Promise((resolve) => setTimeout(resolve, waitTime));
            await this.fetchMainStatus();
        },

        // 更新页面状态
        updataStatus(status) {
            const statusMap = new Map();

            statusMap.set('haveSim', 0);
            statusMap.set('noSim', 1);
            //statusMap.set('simInit', 2);
            statusMap.set('simLock', 3);

            //const isInit = status == 'simInit';
            const simLock = status == 'simLock';
            const showSimSetting = status == 'haveSim';

            const statusArr = [
                // 有卡状态
                {
                    img: this.havecardImg,
                    tipText: this.haveSimTips,
                    nextButton: this.$t('common.nextButton')
                },
                // 无卡状态
                {
                    img: this.insertcardImg,
                    tipText: this.noSimTips,
                    nextButton: this.$t('wizard.version2.skip')
                },
                // 卡初始化提示
                {
                    img: this.simInitImg,
                    tipText: this.simInitTips,
                    nextButton: this.$t('wizard.version2.skip')
                },
                // 锁卡提示
                {
                    img: this.simLockImg,
                    tipText: this.simLocktTips,
                    nextButton: this.$t('wizard.version2.skip')
                }
            ];

            this.img = statusArr[statusMap.get(status)].img;
            this.tipText = statusArr[statusMap.get(status)].tipText;
            //this.isInit = isInit;
            this.simLock = simLock;
        },
    },
    watch: {
        'windowSize.width': {
            handler: function (nVal) {
                this.labelPosition = nVal <= 450 ? 'top' : 'right';
            }
        }
    },
    computed: {
        textPre() {
            return false;
        }
    },
    created() {
        this.fetchMainStatus();
    }
};
</script>

<style lang="less" scoped>
@import '@/assets/css/theme_blue/component_round.less';
@import '@/assets/css/theme_blue/component_common.less';
.page-1 {
    width: 100%;
    height: 100%;
    .card-img {
        height: 250px;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        img {
            width: 152px;
            object-fit: cover;
        }

        .tips-text {
            max-width: 435px;
            text-align: left;
            font-weight: 400;
            padding: 5px;
            box-sizing: border-box;
        }

        .text-pre {
            white-space: pre;
            text-align: center;
        }

        @media (max-width: 600px) {
            .text-pre {
                font-size: 0.8em;
            }
        }
    }

    .btn-content {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100px;

        /deep/.el-button {
            width: 450px;
        }
    }

    .simSettings {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .simSettings-title,
        .simSettings-form {
            width: 50%;
        }

        @media (max-width: 1020px) {
            .simSettings-title,
            .simSettings-form {
                width: 90%;
            }
        }

        .simSettings-title {
            line-height: 50px;
            b {
                min-width: 155px;
                display: inline-block;
                text-align: right;
                padding-right: 12px;
                box-sizing: border-box;
            }
        }

        @media (max-width: 450px) {
            .simSettings-title {
                b {
                    width: auto;
                }
            }
        }
    }
}

@keyframes dot {
    0% {
        content: '...';
    }
    25% {
        content: '';
    }
    50% {
        content: '.';
    }
    75% {
        content: '..';
    }
    100% {
        content: '...';
    }
}

.loading {
    &::after {
        content: '';
        animation: dot 2s infinite;
    }
}

/deep/.el-form-item__label {
    line-height: 52px;
    font-size: 13px;
}

.setWitdh {
    width: 88% !important;
}

@media (max-width: 450px) {
    .setWitdh {
        width: 100% !important;
    }
}

.my-eye-hide,
.my-eye-reveal {
    margin-left: -40px;
    margin-top: 15px;
}
</style>
